import {
  createSlice,
  PayloadAction,
  createAsyncThunk,
  ActionReducerMapBuilder
} from "@reduxjs/toolkit"
import axios from "axios"

interface UserState {
  loading: boolean
  error: string | null
  token: string | null
}

const initialState: UserState = {
  loading: false,
  error: null,
  token: null
}

export const signIn = createAsyncThunk(
  "user/signIn",
  async (
    paramaters: {
      email: string
      password: string
    },
    thunkAPI
  ) => {
    const { data } = await axios.post(`http://123.56.149.216:8080/auth/login`, {
      email: paramaters.email,
      password: paramaters.password
    })
    return data.token
  }
)

export const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    logOut: (state) => {
      state.token = null
      state.error = null
      state.loading = false
    }
  },
  extraReducers: (builder: ActionReducerMapBuilder<UserState>) => {
    builder
      .addCase(signIn.pending, (state) => {
        // 处理pending状态，比如设置加载标志
        // return { ...state, loading: true };
        state.loading = true
      })
      .addCase(signIn.fulfilled, (state, action) => {
        // 处理fulfilled状态，使用action.payload更新state
        state.token = action.payload
        state.loading = false
        state.error = null
      })
      .addCase(signIn.rejected, (state, action) => {
        // 处理rejected状态，比如设置错误信息
        //   const ddd = action.payload;
        state.loading = false
        // state.error = action.payload
      })
  }
})
